#!/bin/bash
set -e

if [ ! -n "${1}" ] ; then
	echo "Usage: ${0} <system dir>"
	exit 0
fi
if [ ! -d "$1/app" ] ; then
	echo "Error. $1/ doesn't contain folder app - this is not the correct system folder."
	exit 1
fi

mkdir -p target_img >/dev/null 2>&1 || true
mkdir -p target_img/temp_sys >/dev/null 2>&1 || true

echo "****** Finding required inode count and required size..."
num_inodes=`sudo find "${1}/" | wc -l`
num_inodes=$(($num_inodes + 500))

req_size=`sudo du -s "${1}/" 2>/dev/null | awk 'function ceil(x) { return (x == int(x)) ? x : int(x)+1 } { printf "%d", ceil((\$1 + \$1 * 5 / 100) / 1024) }'`
echo "****** >> Estimated required size of system.img is ${req_size} MB"

echo "****** Creating ext3 system.img..."
dd if=/dev/zero of=target_img/system.img bs=1M count=${req_size}
echo "y" | mkfs.ext3 -j -L system -N $num_inodes -O dir_index,filetype,sparse_super,has_journal target_img/system.img
echo "****** Disabling auto-checking of system.img"
tune2fs -c -1 -i 0 target_img/system.img

echo ""
echo "****** Copying data..."
sudo mount -o loop target_img/system.img target_img/temp_sys
sudo rsync -a "${1}/" target_img/temp_sys
echo "****** Setting owner..."
sudo chown -R root:root target_img/temp_sys/app/
echo "****** Setting permissions..."
sudo chown 0644 target_img/temp_sys/app/*
echo "****** Unmounting image..."
sudo umount target_img/temp_sys

echo ""
echo "****** Checking and optimizing system.img"
e2fsck -fyD target_img/system.img

sudo rm -rf target_img/temp_sys || true
echo "****** done."
echo ""